package com.dl.test.controller;

import cn.hutool.core.date.DateUtil;
import com.dl.dlcommon.controller.BaseController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * @author DL
 * @create 2022-12-08 14:47
 */
@RestController
@RequestMapping("/sse")
public class SseController extends BaseController {

    @RequestMapping
    public void sse() throws InterruptedException, IOException {
        response.setContentType("text/event-stream");
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        PrintWriter writer = response.getWriter();
        String s = "";
        while (true){
            s = "data: 现在时间是" + DateUtil.now() + "\n\n";
            TimeUnit.SECONDS.sleep(1);
            writer.write(s);
            writer.flush();
        }
    }
}
